import { Module } from 'vuex'
import { IRootState } from '../types'
import { IMainState } from './types'
import localCache from '@/utils/JGLocalCache'

const findIndex = (list: any, page: any) => {
  const itemIndex = list.findIndex((item: any) => {
    return item.path === page.path
  })
  return itemIndex
}

const mainModule: Module<IMainState, IRootState> = {
  namespaced: true,
  state: () => {
    return { historyPage: [] }
  },
  mutations: {
    changeHistoryPage(state, historyPage: any) {
      state.historyPage = historyPage
      localCache.setCache('historyPage', historyPage)
    }
  },
  actions: {
    setHistoryPage({ commit }, page) {
      if (!localCache.getCache('historyPage')) {
        localCache.setCache('historyPage', [])
      }
      const index = findIndex(localCache.getCache('historyPage'), page)
      if (index !== -1) return
      const newArr = localCache.getCache('historyPage').slice()
      newArr.push(page)
      commit('changeHistoryPage', newArr)
    },
    closePage({ commit }, page) {
      const index = findIndex(localCache.getCache('historyPage'), page)
      if (index === -1) return
      const newArr = localCache.getCache('historyPage').slice()
      newArr.splice(index, 1)
      commit('changeHistoryPage', newArr)
      return newArr[index] || newArr[index - 1]
    },
    refreshSetHistoryPage({ commit }) {
      commit('changeHistoryPage', localCache.getCache('historyPage'))
    }
  }
}

export default mainModule
